package io.renren.config;

import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import io.renren.common.utils.RequestDataExtractor;
import io.renren.common.utils.Sign;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

import javax.servlet.FilterConfig;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashSet;

/**
 * @author zhengd
 */
@Slf4j
@Component
public class TokenFilter implements Ordered, Filter {

    @Override
    public int getOrder() {
        // 返回值用来指定执行的顺序，数字越小，优先级越高
        return 0;
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //获取访问路劲
        String path = RequestDataExtractor.getPath(request);
        log.debug("-----------------------访问路径："+path);
        //校验是否是可以直接访问的路径，例如登录接口
        if (!isPass(path)) {
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }
        //从请求头中获取token
        String token = RequestDataExtractor.getHeader(request, "token");
        //校验token
        DecodedJWT decodedJWT = null;
        try {
            decodedJWT = Sign.verifySessionToken(token, "secret");
        } catch (TokenExpiredException e) {
             responseOutWithJson(response, 401, "登录状态已失效，请重新登录");
             return;
        } catch (Exception e) {
            log.info(e.getMessage());
            responseOutWithJson(response, 401, "您还未登录哟");
            return;
        }

        //获取token中解析出的userId

        //String userId = decodedJWT.getClaims().get(Sign.CLAIM_USER_ID).asString();
        //String deptId = decodedJWT.getClaims().get(Sign.CLAIM_DEPT_ID).asString();
        //String userNo = decodedJWT.getClaims().get(Sign.CLAIM_USER_NO).asString();
        //String userName = decodedJWT.getClaims().get(Sign.CLAIM_USER_NAME).asString();
        //Claim roleCodeClaim = decodedJWT.getClaims().get(Sign.CLAIM_ROLE_CODE);
        //Claim roleNameClaim = decodedJWT.getClaims().get(Sign.CLAIM_ROLE_NAME);
        //Claim deptNameClaim = decodedJWT.getClaims().get(Sign.CLAIM_DEPT_NAME);
        //String roleCode = "";
        //String roleName = "";
        //String deptName = "";
        //if (roleCodeClaim != null) {
        //    roleCode = roleCodeClaim.asString();
        //}
        //if (roleNameClaim != null) {
        //    roleName = roleNameClaim.asString();
        //}
        //if (deptNameClaim != null) {
        //    deptName = deptNameClaim.asString();
        //}
        //将userId存入header
        //HeaderMapRequestWrapper headerMapRequestWrapper = new HeaderMapRequestWrapper(request);
        //headerMapRequestWrapper.addHeader("userId",userId);
        //headerMapRequestWrapper.addHeader("deptId",deptId);
        //headerMapRequestWrapper.addHeader("userNo",userNo);
        //headerMapRequestWrapper.addHeader("userName",userName);
        //headerMapRequestWrapper.addHeader("roleCode",roleCode);
        //headerMapRequestWrapper.addHeader("roleName",roleName);
        //headerMapRequestWrapper.addHeader("deptName",deptName);
        filterChain.doFilter(request,servletResponse);
    }

    @Override
    public void init(FilterConfig filterConfig){}

    @Override
    public void destroy() {}

    /**
     * 以JSON格式输出
     * @param response
     */
    protected void responseOutWithJson(HttpServletResponse response,
                                       Integer code, String msg) {
        //将实体对象转换为JSON Object转换
        JSONObject responseJSONObject = new JSONObject();
        responseJSONObject.put("code", code);
        responseJSONObject.put("msg", msg);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter out = null;
        try {
            out = response.getWriter();
            out.print(responseJSONObject.toString());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                out.flush();
                out.close();
            }
        }
    }

    /**
     * 校验不需要token可以直接访问的路径
     */
    private boolean isPass(String path) {
        HashSet<String> paths = new HashSet<>();
        //添加需要拦截的请求路径
        paths.add("/generator/backPay/save");
        paths.add("/generator/backPay/page");
        paths.add("/generator/backPay/info");
        paths.add("/generator/inspection/report");
        paths.add("/generator/inspection/page");
        paths.add("/generator/inspection/info");
        paths.add("/generator/inspection/deal");
        paths.add("/generator/inspection/verify");
        return paths.contains(path) ? true : false;
    }
}

